# -*- encoding:utf-8 -*-
import os
from PIL import Image

# path = r"D:\Work\Project\PublicTools\WebGenerator\ALABS0003G - Coloring Book for Adults - Claming Dream Patterns"

def getAppRes(appPath):
    """遍历文件夹，搜索App Resouce 资源
    @appPath : str: app资源路径，来自于PTS
            For eample:
                r"D:\Work\Project\PublicTools\WebGenerator\ALABS0003G - Coloring Book for Adults - Claming Dream Patterns"
    rt: AppRes Obj
    """
    global searchData 
    searchData = SearchData() 
    
    for i in os.walk(appPath):
        searchFolder(i)
    handleScreenshotsFiles()
    return searchData.appRes


class AppRes(object):
    """
    @screensshots : list(str)
    """
    def __init__(self):
        self.appIcon=""                    # App icon (png 512*512) 路径
        self.featuredPic=""                # featured graphic (jpg, 1024*500) 路径
        self.screenshots=[]                # list screenshots (jpg, 800x1280) 图片路径

class SearchData(object):
    picSuffix=('.jpg','.png')     # 过滤文件后缀
    screenShotsSize=(800,1280)    # screenshot 的图片尺寸
    featuredPicSize=(1024,500)    # featured graphic 图片尺寸
    iconSize=(512,512)            # icon 图片尺寸
    def __init__(self):
        self.appIconTimeStamp = 0          # App icon 文件时间戳，用于找到最新文件
        self.featuredPicTimeStamp = 0      # App featured graphic 文件时间戳，用于找到最新文件
        self.screenshotsTimeStamp = 0      # screenshot 文件时间戳，用于找到最新文件
        self.screenshotsFolder = ""        # 存有最新screenshot 的文件夹
        self.appRes = AppRes()             # 寻找到的资源文件



searchData = SearchData()         # Search 变量

def handleIconFile(fileName):
    """比较icon 文件时间戳，记录最新的icon 文件"""
    statinfo = os.stat(fileName)
    if( statinfo.st_ctime >  searchData.appIconTimeStamp):
        searchData.appRes.appIcon = fileName
        searchData.appIconTimeStamp = statinfo.st_ctime

def handleFeaturedPicFile(fileName):
    """比较featured graphic 文件时间戳，记录最新的featured graphic 文件"""
    statinfo = os.stat(fileName)
    if( statinfo.st_ctime >  searchData.featuredPicTimeStamp):
        searchData.appRes.featuredPic = fileName
        searchData.featuredPicTimeStamp = statinfo.st_ctime

def handleScreenshotsFolder(fileName):
    """比较screenshot 文件时间戳，记录最新的screenshot 所在的文件夹"""
    filePath = os.path.dirname(fileName)
    #print("Screenshot file path: " + filePath)
    statinfo = os.stat(fileName)
    if( statinfo.st_ctime >  searchData.screenshotsTimeStamp):
        searchData.screenshotsTimeStamp = statinfo.st_ctime
        searchData.screenshotsFolder = filePath        

def handleScreenshotsFiles():
    """记录screenshot 所在的文件夹下的所有screenshot 文件"""
    #print("Screenshot path:" + searchData.screenshotsFolder)
    if(searchData.screenshotsFolder != ""):
        files = list(os.walk(searchData.screenshotsFolder))[0][2]
        for i in files:
            fileName = os.path.join(searchData.screenshotsFolder,i)
            if(fileName.lower().endswith(searchData.picSuffix)):
                try:                    
                    im = Image.open(fileName)
                    size = im.size
                    im.close()

                    if(size == searchData.screenShotsSize):
                        #print("parse screenshot file: " + fileName)
                        searchData.appRes.screenshots.append(fileName)
                                
                    
                except:
                    print("Failed to open file: " + fileName)



def parseFile( fileName):
    """ 解析和过滤文件名，图片尺寸"""
    if(fileName.lower().endswith(searchData.picSuffix)):
        try:
            #print("parse file: " + fileName)
            im = Image.open(fileName)
            size = im.size
            im.close()

            if(size == searchData.screenShotsSize):
                handleScreenshotsFolder(fileName)
            elif(size == searchData.featuredPicSize):
                handleFeaturedPicFile(fileName)
            elif(size == searchData.iconSize):
                handleIconFile(fileName)
                                    
        except:
            print("Failed to open file: " + fileName)
                
def searchFolder( folderInfo ):
    """搜索文件夹"""
    #print(folderInfo)
    files = folderInfo[2]
    for i in files:
        parseFile(os.path.join(folderInfo[0],i))
    



def printAppRes(appRes):
    print("####################################################")
    print("App Icon: " + appRes.appIcon)
    print("App Featured pic: " + appRes.featuredPic)
    for i in appRes.screenshots:
        print("App Screenshots: " + i)
    print("####################################################\n")

if __name__=="__main__":
    appRes = getAppRes(path)
    printAppRes(appRes)
